/**
 * This class will work as a link between the data we get from Wowarmory and 
 * mmo-champion.
 * 
 * This is how this thingie works:
 * 
 * We sends a request for the following page:
 * 
 * http://db.mmo-champion.com/i/29502
 * 
 * EXPLAINED:
 * 
 * http://db.mmo-champion.com/i/<ITEM_ID_FROM_WOW_ARMORY_COM>
 * 
 * <ITEM_ID_FROM_WOW_ARMORY_COM> = This is the ID we get from an item for a char.
 * 
 * E.g:
 * 
 * <item displayInfoId="45844" durability="46" gem0Id="0" 
 * gem1Id="0" gem2Id="0" icon="inv_helmet_38" id="29502" 
 * level="105" maxDurability="70" name="Cobrascale Hood" 
 * ....../>
 * 
 * Where the link for this item would be as follows:
 * 
 * <a href="http://db.mmo-champion.com/i/29502">Cobrascale Hood</a>
 * 
 * Then we save the correctsponding image - and maps its location in a xml file..
 * 
 */

package wowmmodb;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.HasParentFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;
import org.htmlparser.util.Translate;

import charactergear.CharacterGearType;

public class MmoChampionItemImport {
	
	private static final String[] IMAGE_FILE_TYPE = {".png", ".jpg", ".bmp"};
	private static final String SOURCE_OF_ITEMS = "http://db.mmo-champion.com/i/";
	private static final String PATH_TO_IMAGEREPO = "http://db.mmo-champion.com/static/img/icons/";
	private static final String SEPERATOR = "/";
	private static final String USER_HOME = System.getProperty("user.home");

	public MmoChampionItemImport() {
		
	}
	
	/**
	 * NOTE: mmochampion using the same id-pattern as wowarmory does
	 * So if an item with ID = <something> from wowarmory, than this
	 * ID will match the string for mmochampion's db..
	 * 
	 * 
	 * TODO: Change this method to return <ITEM>-object type..
	 * @param itemId = identifier from wowarmory.
	 * @return Object
	 * @throws some exceptions..
	 */
	
	public Object retrieveItemData(Integer itemId, String itemName) {
		CharacterGearType gearType = CharacterGearType.UNDEFINED;
		try{
			print("\t o) Fetching data for item: " + itemId);
			
			Parser htmlParser = new Parser(
					SOURCE_OF_ITEMS + 
					itemId + 
					SEPERATOR
					//+ (!itemName.equals("") || itemName!=null) != null ? itemName : ""
					);
			
			NodeFilter nodeFilter = new HasParentFilter(new HasAttributeFilter("id", "sitenav"));
			NodeList nodeList = htmlParser.extractAllNodesThatMatch(nodeFilter);
		
			SimpleNodeIterator iterator = nodeList.elements();
			
			while(iterator.hasMoreNodes()) {
				Node node = iterator.nextNode();
				if(node.toHtml().contains("Weapon")) {
					gearType = CharacterGearType.WEAPON;
					break;
				}else{
					gearType = CharacterGearType.ARMOR;
				}
			}
			
			print("\t o) Current item is of type {WEAPON, ARMOR}: " + gearType.toString() + "...");
			
			/*
			 * Fetching image for the current item
			 */
			
			htmlParser.reset();
			NodeFilter currItemImageFilter = new AndFilter(new TagNameFilter("a"), 
					new HasParentFilter(new TagNameFilter("h1")));
			TagNode currItemImageNode = 
				(TagNode) htmlParser.extractAllNodesThatMatch(currItemImageFilter).elementAt(0); // must use this!! (def. href)
			
			//print("Current itemImageNode: *TEStING ONLY: " + currItemImageNode);
			
			String urlHref = currItemImageNode.getAttribute("href");
			String image = urlHref.substring(12);
			String imageName = Translate.decode(currItemImageNode.getParent().getLastChild().toString().trim());
			int seperatorForImageName = imageName.indexOf(":");
			imageName = imageName.substring(seperatorForImageName+2);
			print("\t o) Loaded image url: " + image + "\r\t o) Loaded item name: " + imageName);
			
			boolean savedImage = false;
			try {
				savedImage = retrieveImageAndSaveIt(new URL(PATH_TO_IMAGEREPO + image + IMAGE_FILE_TYPE[0]), 
						image);
			} catch (MalformedURLException e) {
				//WILL NEVER HAPPEN
				e.printStackTrace();
			} catch (IOException e) {
				//CAN HAPPEN!!
				e.printStackTrace();
			}
			
			print((savedImage) ? "\t\tImage saved to $PATH" : "\t\tImage already exists!/Something went wrong!");
			
			return new Object(); // CHANGE THIS TO ITEM..ARMOR..W/E..
		} catch (ParserException e){
			print(e);
			return null; // NOT NULL PLEASE..THIS IS JUST A TEMP VALUE..
		}
	}
	
	/**
	 * 
	 * @param url
	 * @param fileName
	 * @return true if everything went fine, otherwise ; false..
	 * @throws IOException
	 */
	
	protected boolean retrieveImageAndSaveIt(URL url, String fileName)
	throws IOException {
		BufferedImage itemImage = null;
		itemImage = ImageIO.read(url); // SOURCE_OF_ITEMS + itemId.toString() + SEPERATOR
		File itemFile = new File(USER_HOME + SEPERATOR + fileName + IMAGE_FILE_TYPE[0]);
		print("\t o) Saving file to location: " + itemFile.getCanonicalPath());
		if(itemFile.exists()) {
			return false;
		} else {
			//TODO: CREATE / UPDATE XML FILE FOR DATA CONTAINING THIS PROGRAM
			//ImageIO.write(itemImage, IMAGE_FILE_TYPE[0].substring(1).toUpperCase(), itemFile);
			return true;
		}
	}
	
	private void print(Object something) {
		System.out.println(something.toString());
	}
	
}
